package servlet.events;
import java.io.IOException;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.EmailSender;
import util.FormValidation;

import bundle.ErrorsBundleKey.UserErrorBundleKey;

public class ContactHandler extends EventHandler {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		if (validateForm(request) && (sendEmail(request))) {
			request.setAttribute("status", "ok");		
		}
		else {
			request.setAttribute("status", "error");
		}
		forward(urlBundle.getString("CONTACT_URL"), request, response);
	}	
	
	private boolean sendEmail(HttpServletRequest request) {
		EmailSender sender = new EmailSender();
		sender.setFirstnameSender(request.getParameter(FIRSTNAME));
		sender.setLastnameSender(request.getParameter(LASTNAME));
		sender.setEmailSender(request.getParameter(EMAIL));
		
		String subject = request.getParameter(SUBJECT);
		String text = request.getParameter(TEXT);
		try {
			sender.send(subject, text);
			return true;
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	private boolean validateForm(HttpServletRequest request) {
		int i = 0;
		
		if(request.getParameter(LASTNAME) == null || request.getParameter(LASTNAME).trim().equals("")){
			setErrors(UserErrorBundleKey.LASTNAME_NOT_NULL, request);
			i++;
		}
		
		if(request.getParameter(FIRSTNAME) == null || request.getParameter(FIRSTNAME).trim().equals("")){
			setErrors(UserErrorBundleKey.FIRSTNAME_NOT_NULL, request);
			i++;
		}	
		
		if (request.getParameter(EMAIL) == null || request.getParameter(EMAIL).trim().equals("")){
			setErrors(UserErrorBundleKey.EMAIL_NOT_NULL, request);
			i++;
		}
		//else if (!user.getEmail().matches("^[a-zA-Z0-9]+([-+.'][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-.][a-zA-Z0-9]+)*\.[a-zA-Z0-9]+([-.][a-zA-Z0-9]+)*$") {
		else if(!FormValidation.validateEmail(request.getParameter(EMAIL))){
			setErrors(UserErrorBundleKey.EMAIL_INVALID, request);
			i++;
		}
		
		if(request.getParameter(SUBJECT) == null || request.getParameter(SUBJECT).trim().equals("")){
			setErrors(UserErrorBundleKey.SUBJECT_NOT_NULL, request);
			i++;
		}
		
		if(request.getParameter(TEXT) == null || request.getParameter(TEXT).trim().equals("")){
			setErrors(UserErrorBundleKey.TEXT_NOT_NULL, request);
			i++;
		}
		
		if (i == 0)
			return true;
		
		return false;
	}

	private static final String LASTNAME = "lastname";
	private static final String FIRSTNAME = "firstname";
	private static final String EMAIL = "email";
	private static final String SUBJECT = "subject";
	private static final String TEXT = "text";
}
